package com.nchuAo.controller;

import com.nchuAo.util.PageResult;
import com.nchuAo.util.Response;
import com.nchuAo.entity.Goods;
import com.nchuAo.service.GoodsService;
import com.nchuAo.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/Goods")
public class GoodsController {

	@Autowired
	private GoodsService GoodsService;

	// 商品列表
	@RequestMapping("/list")
	public Response getGoods() {
		return Response.ok().data("list",GoodsService.list());
	}

	// 分页查询
	@GetMapping("/findByPage/{page}/{pageSize}")
	public Response findByPage(@PathVariable("page") Integer page,
							   @PathVariable("pageSize") Integer pageSize) {
		PageResult<Goods> pageResult = GoodsService.findByPage(page,pageSize);
		return Response.ok().data("pageResult",pageResult);
	}

	// 条件带分页查询
	@PostMapping("/search/{page}/{pageSize}")
	public Response search(@PathVariable("page") Integer page,
						   @PathVariable("pageSize") Integer pageSize,
						   @RequestBody(required = false) GoodsVO vo){
		PageResult<Goods> pageResult = GoodsService.search(page,pageSize,vo);
		return Response.ok().data("pageResult",pageResult);
	}

	// 添加商品
	@PostMapping("/add")
	public Response add(@RequestBody Goods Goods){
		boolean flag = GoodsService.add(Goods);
		return flag ? Response.ok().message("添加商品成功!") : Response.error().message("添加商品失败!");
	}

	//修改商品
	@PutMapping("/update")
	public Response update(@RequestBody Goods Goods){
		boolean flag = GoodsService.updateById(Goods);
		return flag ? Response.ok().message("修改商品成功!") : Response.error().message("修改商品失败!");
	}


	// 删除商品
	@DeleteMapping("/delete/{ids}")
	public Response delete(@PathVariable("ids") String ids){  // 1,2,3
		String[] split = ids.split(",");
		List<String> sids = Arrays.asList(split);
		return GoodsService.removeByIds(sids) ? Response.ok().message("删除商品成功!") : Response.error().message("删除商品失败!");
	}
}
